package com.feihao.zhou.ThreadSaveDemo3;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class ChiHuo implements Runnable {
    private Desk desk;

    public ChiHuo(Desk desk) {//通过构造方法将锁对象传进来
        this.desk = desk;
    }

    @Override
    public void run() {
        while (true){
            synchronized (desk){
                if (desk.getCount() == 0){//如果没有包子
                    break;
                }
                if (desk.isFlag()){
                    //有包子，则开吃
                    System.out.println("吃货在吃包子");
                    desk.setFlag(false);//吃完后将状态设置为false
                    int i = desk.getCount() - 1;  //将包子制作次数-1后再设置
                    desk.setCount(i);
                    //叫醒厨师制作包子：
                    desk.notify();
                }else {
                    //则等待：
                    try {
                        desk.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}
































/*    public Desk desk;

    public ChiHuo(Desk desk) {
        this.desk = desk;
    }

    //    Lock lock = new ReentrantLock();(锁不能设置在线程当中！！！)
    @Override
    public void run() {
        while (true) {
            synchronized (desk.getLock()) {
                if (desk.getCount() == 0) {
                    break;
                } else {
                    if (desk.isFlag()) {//有包子
                        try {
                            Thread.sleep(100);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        System.out.println("吃货正在吃包子");
                        desk.setCount(desk.getCount()-1);
                        desk.setFlag(false);
                        desk.getLock().notify();
                    } else {
                        try {
                            desk.getLock().wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
    }
}*/
